# -*- coding:utf-8 -*-
# @FileName  :数据库练习.py
# @Time      :2021-01-23 13:53
# @Author    :niuhanyang

import pymysql
import traceback
mysql_info = {
    "host":"118.24.3.40",
    "user":"jxz",
    "password":"123456",
    "db":"jxz",
    "port":3306,
    "charset":"utf8",
    "autocommit":True
}
def execute_sql(sql,more=True,db_info=None):
    #select * from user;
    #select * from user where id = 1;
    try:
        if db_info:
            conn = pymysql.connect(**db_info)
        else:
            conn = pymysql.connect(**mysql_info) #host=xxx,user=xx
    except Exception:
        traceback.print_exc()
        return 3#数据库连接失败
    cursor = conn.cursor(pymysql.cursors.DictCursor)
    try:
        cursor.execute(sql)
    except:
        print("sql语句不正确 %s" % sql)
        return 4 #代表sql不正确
    else:
        if more:
            result = cursor.fetchall()
        else:
            result = cursor.fetchone()
    finally:
        cursor.close()
        conn.close()
    return result



if __name__ == '__main__':
    result = execute_sql("select * from students1 limit 5;")
    print(result)